package com.yaorange.module.security.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.yaorange.exception.BusinessException;
import com.yaorange.module.security.entity.dto.LoginDTO;
import com.yaorange.module.security.repository.AuthRepository;
import com.yaorange.module.security.service.AuthService;
import com.yaorange.module.system.service.SysUserService;
import com.yaorange.pojo.SysUser;
import com.yaorange.response.enums.ResultCode;
import com.yaorange.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 15332
 * @version 1.0
 * @date 2025/6/20 16:07
 * @description 登录认证业务层
 */
@Service
public class AuthServiceImpl implements AuthService {
  @Autowired
  private SysUserService service;
  @Autowired
  private JwtUtil jwtUtil;

  @Override
  public String login(LoginDTO loginDTO) {
    SysUser user = service.getUserByName(loginDTO.getUsername());
    if (user==null){
      throw new BusinessException(ResultCode.USER_FAILED);
    }
    // 校验密码
    // 对传输的数据进行加密，使用Hutool工具
    String s = SecureUtil.md5(loginDTO.getPassword());
    if (!user.getUserPassword().equals(loginDTO.getPassword())){
      throw new BusinessException(ResultCode.USER_FAILED);
    }
    // 令牌中需要携带的数据
    Map<String, Object> claims = new HashMap<>();
    claims.put("id",user.getUserId());
    claims.put("Nickname",user.getUserNickname());
    claims.put("Avatar",user.getUserAvatar());
    claims.put("admin",user.getAdmin());
    // 生成令牌
    String token = jwtUtil.generateToken(claims);
    return token;
  }
}
